package gologger

import (
	"fmt"
	"os"
	"path"
	"runtime"
	"strings"
	"time"
)

type LogLevel uint

const (
	UNKNOWN LogLevel = iota
	DEBUG
	INFO
	WARNING
	ERROR
	FATAL
)

type LogOutPut interface {
	DEBUG(fotmat string, a ...interface{})
	INFO(fotmat string, a ...interface{})
	WARNING(fotmat string, a ...interface{})
	ERROR(fotmat string, a ...interface{})
	FATAL(fotmat string, a ...interface{})
	logFotmatOutput(lv LogLevel, fotmat string, a ...interface{})
}

var Default *ConsoleLogger

//格式化输出信息
func FotmatLog(loglevel, outPutType string, path ...string) LogOutPut {
	outPutType = strings.ToUpper(outPutType)
	switch outPutType {
	case "FILE":
		if len(path) == 1 {
			_, err := os.Stat(path[0])
			//创建目录
			if err != nil {
				if os.IsNotExist(err) {
					if err := os.Mkdir(path[0], os.ModePerm); err != nil {
						fmt.Println(err)
					}
				} else {
					panic("无法创建日志目录")
				}
			}
			logpath := path[0] + "/"
			return NewFileLogger(loglevel, logpath, "log", 100*1024*1024)
		} else {
			return NewFileLogger(loglevel, "./", "log", 100*1024*1024)
		}

	case "CONSOLE":
		filelog := NewConsoleLogger(loglevel)
		return filelog
	default:
		filelog := NewConsoleLogger(loglevel)
		return filelog
	}

}

//字符转换为level
func paseLogLevel(s string) (LogLevel, error) {
	s = strings.ToUpper(s)
	switch s {
	case "DEBUG":
		return DEBUG, nil
	case "INFO":
		return INFO, nil
	case "WARNING":
		return WARNING, nil
	case "ERROR":
		return ERROR, nil
	case "FATAL":
		return FATAL, nil
	default:
		return UNKNOWN, nil
	}
}

//level转换为string
func getLogString(level LogLevel) string {
	switch level {
	case DEBUG:
		return "DEBUG"
	case INFO:
		return "INFO"
	case WARNING:
		return "WARNING"
	case ERROR:
		return "ERROR"
	case FATAL:
		return "FATAL"
	default:
		return "DEBUG"
	}
}

//获取日志所在执行行的相关信息（文件名，函数名，行号）
func getInfo(skip int) (funcName, fileName string, lineNo int, timestamp string) {
	pc, file, lineNo, ok := runtime.Caller(skip)
	if !ok {
		fmt.Println("runtime,caller() failed")
		return
	}
	funcName = runtime.FuncForPC(pc).Name()
	fileName = path.Base(file)
	timestamp = time.Now().Format("2006/01/02 03:04:05")
	return
}

func init() {

	//只占用一个线程，避免干扰业务
	// runtime.GOMAXPROCS(1)
	Default = NewConsoleLogger("debug")
}
